package cn.itrip.auth.service.impl;

import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.Token;
import cn.itrip.common.*;
import cn.itrip.dao.mapper.ItripUserMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/11/21.
 *  *  用户认证业务：3 开头（30000）
 *  操作成功为(30000)
 *  操作失败为(30001)
 *  异常为(30002)
 **/
@Service
@Component
public class UserServiceImpl implements UserService {

    Logger logger  =  Logger.getLogger(UserServiceImpl.class);
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private  RedisTemplate redisTemplate;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SimpleMailMessage mailMessage;
    @Resource
    private MailSender mailSender;











    //登录
    public Dto selectByLogin(String userCode, String userPassword,String platformname){
        if(platformname.equals("UNKNOWN")){
            platformname="PC";
        }
        ItripUser user= null;
        ItripUser user1= null;
        try {
            user = itripUserMapper.selectByLogin(userCode,userPassword);
            user1=itripUserMapper.selectByUserCode(userCode);
        } catch (Exception e) {
            //打印异常信息
            logger.debug("出错了"+e);
            return DtoUtils.getExcetpionDto(e,"30002");
        }
         if(!(null!=user1)){
             return DtoUtils.getErrorDto("帐号不存在，请去注册", "30001");
         }
        if(user != null) {
            //判断当前是否存在
            //判断当前用户是否激活
            if(user.getActivated()==0){
                return DtoUtils.getErrorDto("帐号未激活", "30001");
            }

            StringBuilder sb = new StringBuilder();
            //追加拼接
            sb.append("token:" + platformname + "-"
                    + Md5Util.encode(user.getUserCode()) +
                    "-" + user.getId() + new SimpleDateFormat("yyyyyMMddHHmmss").format(new Date())
                    + "-" + ValiditorCodeUtil.getCode(6));
            //创建token
            Token token = new Token();
            token.setToken(sb.toString());
            //格式化日期
            token.setGenTime(System.currentTimeMillis());
            //判断当前是否是PC端登录，客户端返回为UNKNOWN
            if (platformname.equals("PC")) {
                //PC端登录设置客户端token有效期为2个小时
                token.setExpTime(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
                redisUtil.setValueExpire(sb.toString(), JSON.toJSONString(user), 2 * 60 * 60);
            } else {
                //手机端或者平板登录，token设置为不失效
                token.setExpTime(Long.MAX_VALUE);
                redisUtil.setValue(sb.toString(), JSON.toJSONString(user));
            }
            return DtoUtils.getSuccesDto(token);
        }
        return DtoUtils.getErrorDto("帐号密码错误", "30001");
    }
    public Dto selectByUserCode(String userCode) {
        ItripUser user= null;
        try {
            user = itripUserMapper.selectByUserCode(userCode);
        } catch (Exception e) {
            //打印异常信息
            logger.debug("出错了"+e);
            return DtoUtils.getExcetpionDto(e,"30002");
        }
        //判断该userCode是否已被注册
        if(null!=user){
            return DtoUtils.getErrorDto("已经存在了","30001");
        }
        return DtoUtils.getSuccesDto("30000");
    }
    //注销
    public Dto logout(String token) {
        //根据用户传进来的token获取用户的信息
        if (redisUtil.getValue(token)!=null) {
            redisUtil.del(token);
        }
        //删除reids中的信息
        return DtoUtils.getSuccesDto("30000");
    }
    //替换token
    public Dto reloadToken(String token2) {
        String userjson= redisUtil.getValue(token2);
        //判断token是否已经失效
        if(redisUtil.getValue(token2)==null){
            return DtoUtils.getErrorDto("已经不存在了","30001");
        }
        //重新生成一个新的token
        StringBuilder sb=new StringBuilder();
        ItripUser user= JSONObject.parseObject(userjson,ItripUser.class);
        sb.append("token:PC-"
                +Md5Util.encode(user.getUserCode())+
                "-"+user.getId()+new SimpleDateFormat("yyyyyMMddHHmmss").format(new Date())
                +"-"+ValiditorCodeUtil.getCode(6));
        Token token=new Token();
        token.setToken(sb.toString());
        token.setGenTime(System.currentTimeMillis());
        token.setExpTime(System.currentTimeMillis()+2*60*60*1000);
        redisUtil.setValueExpire(sb.toString(),userjson,2*60*60);
        redisUtil.setValueExpire(token2,userjson,10*60);
        return DtoUtils.getSuccesDto(token);
    }
    //邮箱注册
    public Dto emailRegedit(ItripUser user) throws Exception {
        //当前时间
        user.setCreationDate(new Date());
        //添加默认为不激活状态
        user.setActivated(0);
        //调用获取usercode方法
        ItripUser user1=itripUserMapper.selectByUserCode(user.getUserCode());
        //进行添加
        int num= 0;
        try {
            //防止重复提交
            if(user1!=null){
                return DtoUtils.getErrorDto("不能重复注册相同帐号","30001");
            }
            num = itripUserMapper.insert(user);
        } catch (Exception e) {
            //打印异常信息
            logger.debug("出错了"+e);
            return DtoUtils.getExcetpionDto(e,"30002");
        }
        //判断是否注册成功
        if(num>0){
            //生成一个验证码 保存到redis
            String code= ValiditorCodeUtil.getCode(16);
            //设置失效时间
            redisUtil.setValueExpire(user.getUserCode(),code,24*60*60);
            //发送邮件给客户
            mailMessage.setText("欢迎注册爱旅行,您的验证码是"+code);
            //显示时间为当前时间
            mailMessage.setSentDate(new Date());
            //发送的对象
            mailMessage.setTo(user.getUserCode());
            mailSender.send(mailMessage);
            //结果
            return DtoUtils.getSuccesDto("30000");
        }
        return DtoUtils.getErrorDto("错误","30001");
    }
    //手机注册
    public Dto phoneRegedit(ItripUser user) {
        //当前时间
        user.setCreationDate(new Date());
        //添加默认为不激活状态
        user.setActivated(0);
        int num= 0;
        try {
            num = itripUserMapper.insert(user);
        } catch (Exception e) {
            //打印异常信息
            logger.debug("出错了"+e);
            return DtoUtils.getExcetpionDto(e,"30002");
        }
        if(num>0){
            //发送手机号方法
            //phone.getcode(user.getUserCode());
            String authCode=phone.getcode(user.getUserCode());
            redisUtil.setValue(user.getUserCode(),authCode);
            return DtoUtils.getSuccesDto("30000");
        }
        return DtoUtils.getErrorDto("错误","30001");
    }
    //激活用户
    public Dto updateActivated(String userCode, String code){
        //从redis中根据name取中, 和传入的进行对比
        if(null==redisUtil.getValue(userCode)){
            return DtoUtils.getErrorDto("帐号不存在","30001");
        }
        //判断是否一致
        if (code.equalsIgnoreCase(redisUtil.getValue(userCode))) {
            //调用激活方法
            int num= 0;
            try {
                num = itripUserMapper.updateActivated(userCode);
            } catch (Exception e) {
                //打印异常信息
                logger.debug("出错了"+e);
                return DtoUtils.getExcetpionDto(e,"30002");
            }
            if (num>0){
                //删除存在redis中的数据
                redisUtil.del(userCode);
                return DtoUtils.getSuccesDto("30000");
            }
        }
        return DtoUtils.getErrorDto("帐号和激活码不一致","30001");
    }
}
